package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        // 1. 查询待付款订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        if (ordersList !=null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                // 2. 将订单状态设置为已取消
                orders.setStatus(Orders.CANCELLED);
                // 3. 设置取消原因
                orders.setCancelReason("订单超时，已自动取消");
                // 4. 设置取消时间
                orders.setCancelTime(LocalDateTime.now());
                // 5. 更新订单
                orderMapper.update(orders);
            }
        }
    }
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理派送中订单：{}", LocalDateTime.now());
        // 1. 查询派送中订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusMinutes(60));
        if (ordersList !=null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                // 2. 将订单状态设置为已完成
                orders.setStatus(Orders.COMPLETED);
                // 3. 更新订单
                orderMapper.update(orders);
            }
        }
    }
}
